import axios from 'axios'
import {Loading} from 'element-ui'
import {getToken} from './auth.js'
const loading = {
  // 保存loading实例对象
  loadingInstance : null,
  // 开启loading方法
  open: function(){
    if(this.loadingInstance==null) {
      this.loadingInstance = Loading.service({
        target: '.main',
        background: 'rgba(0,0,0,0.5)',
        text: '拼命加载中'
     })
    }
  },
  // 关闭loading方法
  close: function(){
    if(this.loadingInstance!==null) {
      this.loadingInstance.close()
    }
    this.loadingInstance = null
  }
}

const request = axios.create({
//   公共地址
  baseURL: process.env.VUE_APP_BASE_API,
//   超时时间
  timeout: 5000
})
// 请求拦截
request.interceptors.request.use(function (config) {
  // 开启loading
  loading.open()
  if(getToken()){
    config.headers.authorization ="Bearer " + getToken()
  }
  return config;
}, function (error) {
  // 关闭loading
  loading.close()
  return Promise.reject(error);
});
  
// 创建响应拦截器
request.interceptors.response.use(function (response) {
  // 关闭loading
  loading.close()
  return response.data;
}, function (error) {
  // 关闭loading
  loading.close()
  return Promise.reject(error);
});
export default request